import { listGeneratorVoByPageUsingPost } from '@/services/backend/generatorController';
import { UserOutlined } from '@ant-design/icons';
import { PageContainer, ProFormSelect, ProFormText, QueryFilter } from '@ant-design/pro-components';
import { Avatar, Card, Flex, Image, List, message, Tabs, Tag, Typography } from 'antd';
import Search from 'antd/es/input/Search';
import moment from 'moment';
import React, { useEffect, useRef } from 'react';
import { Link } from 'umi';

const DEFAULT_PAGE_PARAMS: PageRequest = {
  current: 1,
  pageSize: 4,
  sortField: 'createTime',
  sortOrder: 'descend',
};
const IndexPage: React.FC = () => {
  const [loading, setLoading] = React.useState<boolean>(true);
  const [dataList, setDataList] = React.useState<API.GeneratorVO[]>([]);
  const [total, setTotal] = React.useState<number>(0);
  const [searchParam, setSearchParam] = React.useState<API.GeneratorQueryRequest>({
    ...DEFAULT_PAGE_PARAMS,
  });
  const searchRef = useRef();
  const doSearch = async () => {
    setLoading(true);
    try {
      const res = await listGeneratorVoByPageUsingPost(searchParam);
      setDataList(res.data?.records ?? []);
      setTotal(res.data?.total ?? 0);
    } catch (e: any) {
      message.error('获取数据失败', e.message);
    }
    setLoading(false);
  };
  useEffect(() => {
    doSearch();
  }, [searchParam]);
  const tagListView = (tags: string[]) => {
    if (!tags) return;
    return tags.map((item, index) => <Tag key={index}>{item}</Tag>);
  };
  return (
    <PageContainer title={<></>}>
      <Flex justify={'center'}>
        <Search
          style={{
            width: '40vw',
            minWidth: '320',
          }}
          ref={searchRef as any}
          placeholder="搜索"
          allowClear
          enterButton="搜索"
          size="large"
          onSearch={(value: string) => {
            setSearchParam({
              ...DEFAULT_PAGE_PARAMS,
              searchText: value,
            });
          }}
        />
      </Flex>

      <Tabs
        defaultActiveKey="1"
        onChange={() => {}}
        items={[
          {
            label: `最新`,
            key: '1',
            children: ``,
          },
          {
            label: `推荐`,
            key: '2',
            children: ``,
          },
        ]}
      />
      <QueryFilter
        span={12}
        labelWidth={'auto'}
        labelAlign={'left'}
        defaultCollapsed={false}
        style={{ padding: '16px 0' }}
        split
        onFinish={(value: API.GeneratorQueryRequest) => {
          setSearchParam({
            ...DEFAULT_PAGE_PARAMS,
            //@ts-ignore
            searchText: searchRef.current?.input.value,
            ...value,
          });
        }}
      >
        <ProFormSelect label="标签" mode="tags" name="tags" />
        <ProFormText label="名称" name="name" />
        <ProFormText label="描述" name="description" />
      </QueryFilter>
      <List<API.GeneratorVO>
        rowKey="id"
        grid={{
          gutter: 16,
          xs: 1,
          sm: 2,
          md: 3,
          lg: 3,
          xl: 4,
          xxl: 4,
        }}
        pagination={{
          current: searchParam.current,
          pageSize: searchParam.pageSize,
          total: total,
          onChange: (current, pageSize) => {
            setSearchParam({
              ...searchParam,
              current: current,
              pageSize: pageSize,
            });
          },
        }}
        loading={loading}
        dataSource={dataList}
        renderItem={(data) => (
          <List.Item key={data.id}>
            <Link to={`/generator/detail/${data.id}`}>
              <Card hoverable cover={<Image alt={data.name} src={data.picture} />}>
                <Card.Meta
                  title={data.name}
                  description={
                    <Typography.Paragraph
                      ellipsis={{ rows: 2 }}
                      style={{
                        height: 44,
                      }}
                    >
                      {data.description}
                    </Typography.Paragraph>
                  }
                />
                {tagListView(data?.tags ?? [])}
                <Flex justify={'space-between'} align={'center'}>
                  <Typography.Paragraph type="secondary" style={{ fontSize: 12 }}>
                    {moment(data.createTime).fromNow()}
                  </Typography.Paragraph>
                  <div>
                    <Avatar src={data.user?.userAvatar ?? <UserOutlined />} />
                  </div>
                </Flex>
              </Card>
            </Link>
          </List.Item>
        )}
      ></List>
    </PageContainer>
  );
};

export default IndexPage;
